import axios from 'axios'
import { useUserStore } from '@/stores/index.js'
import { ElMessage } from 'element-plus'
import router from '@/router/index.js'

const baseURL = 'http://localhost:8080'

const instance = axios.create({
  baseURL,
  timeout: 50000
})


instance.interceptors.request.use(
  (config) => {
    const useStore = useUserStore()
    if (useStore.token) {
      config.headers.token = useStore.token
    }
    return config
  },
  (err) => Promise.reject(err)
)

instance.interceptors.response.use(
  //有返回值
  (res) => {
    if (res.data.code === 0) {
      return res
    }
    ElMessage.error(res.data.message || '有猪比不写错误提示')
    return Promise.reject(res.data)
  },
  (err) => {
    if (err.data?.status === 401) {
      router.push('/login')
    }
    ElMessage.error(err.data.message || '有猪比不写错误提示')
    return Promise.reject(err)
  }
)

export default instance
export { baseURL }

